<template>
  <div class="element-table">
    <div class="el-head">
      <div class="table-left">
        <el-button class="table-button-left" type="primary" @click="handleUpload()">新增</el-button>
      </div>
      <div class="table-right">
        <el-input class="table-input-right" placeholder="分类名字" @keyup.enter.native="clickQuery" clearable v-model="categoryName"/>
        <el-button class="table-button-right" @click="clickQuery" type="primary">查询</el-button>
      </div>
    </div>
    <div>
      <el-table :data="dataList" border>
        <el-table-column v-slot="scope" label="分类名字" align="center">
          {{ scope.row.categoryName }}
        </el-table-column>
        <el-table-column v-slot="scope" label="上架时间" align="center">
          {{ scope.row.createDate }}
        </el-table-column>
        <el-table-column v-slot="scope" label="操作" align="center">
          <el-button type="primary" round size="mini" class="table-button-param" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="danger" round size="mini" class="table-button-param" @click="handleDelete(scope.row)">删除</el-button>
        </el-table-column>
      </el-table>
      <el-pagination background :current.sync="pageNo" class="page" layout="total,prev,pager,next" @current-change="change"
        :total="pageTotal" align="center"></el-pagination>
    </div>
    <div>
      <el-dialog title="详情图" width="45%" :visible.sync="imgModal" destroy-on-close close-on-press-escape lock-scroll>
        <img :src="imgName" class="image-details" alt="">
      </el-dialog>
      <el-dialog width="45%" :visible.sync="dataFlag" destroy-on-close :close-on-click-modal="false" close-on-press-escape>
        <div slot="title" style="display: flex;justify-content: center;font-weight: bold;">
          {{ dataTitle }}
        </div>
        <el-form ref="dataDetails" :rules="ruleValidate" :model="dataDetails" label-width="120px" @submit.native.prevent>
          <el-form-item label="分类名字：" prop="categoryName">
            <el-input v-model="dataDetails.categoryName" :maxlength="20" show-word-limit class="form-input"/>
          </el-form-item>
          <el-form-item>
            <el-button @click="dataFlag=false">取 消</el-button>
            <el-button type="primary" v-preventReClick @click="handleSubmit('dataDetails')">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import '@/styles/style.scss'
import '@/styles/upload.scss'
import {formatDate, ossPut, isBlank, isFlag, moneyFormat, initCacheData} from '@/utils/util'
import appUtils from '@/utils/util'
import {imageUtils} from '@/utils/imageUtil'
import {displayWindowPartnerCategoryDelete, displayWindowPartnerCategoryPojoList, displayWindowPartnerCategoryPojoOperation} from '@/api/display'
import {beforeRouteEnterCopy, beforeRouteLeave} from '@/utils/pageUtil'
import CoverUpload from "@/components/Upload/coverUpload";
import AvatarUpload from "@/components/Upload/avatarUpload";
import ruleUtils from "@/utils/ruleUtils";

export default {
  name: 'displayWindowPartnerCategoryList',
  components: {AvatarUpload, CoverUpload},
  data() {
    return {
      pageNo: 1,
      pageTotal: 0,
      paId: this.$store.state.user.userId,
      seriesId: this.$route.query.seriesId,
      myImage: appUtils.myImage,
      imageImg: appUtils.imageImg,
      categoryName: '',
      imgName: '',
      dataTitle: '',
      dataFlag: false,
      dataDetails: {},
      ruleValidate: {
        categoryName: [{
          required: true,
          message: "必填项",
          validator: ruleUtils.nullValidator,
          trigger: "blur",
        }],
      },
      imgModal: false,
      dataList: [],
      routerPage: [],
      dataListCopy: [],
    }
  },
  methods: {
    formatDate,
    ossPut,
    isBlank,
    isFlag,
    moneyFormat,
    imageUtils,
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.dataDetails.paId = this.paId
          let dataDetailsJson = JSON.stringify(this.dataDetails)
          console.log(dataDetailsJson)
          displayWindowPartnerCategoryPojoOperation(dataDetailsJson).then(res => {
            console.log(res)
            if (isFlag(res.code, 1)) {
              this.$message.success(res.message)
              this.$refs['dataDetails'].resetFields()
              this.dataFlag = false
              setTimeout(() => {
                this.change(this.pageNo)
              }, 200)
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    clickQuery() {
      this.change(1)
    },
    changeSel() {
      this.change(1)
    },
    async change(page) {
      this.pageNo = page
      displayWindowPartnerCategoryPojoList(this.pageNo, this.paId, this.categoryName).then(res => {
        console.log(res.data)
        this.dataList = res.data.dataList.map((value, index) => {
          value.createDate = formatDate(new Date(value.createDate), 'yyyy-MM-dd hh:mm')
          return value
        })
        this.dataListCopy = JSON.parse(JSON.stringify(res.data.dataList))
        this.pageTotal = res.data.count
      })
    },
    handleImage(src, name) {
      this.imgName = imageUtils(src, name)
      this.imgModal = true
    },
    handleDelete(param) {
      this.$confirm('是否确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        displayWindowPartnerCategoryDelete(param.cateId).then(res => {
          if (isFlag(res.code, 1)) {
            this.$message.success(res.message)
            this.change(this.pageNo)
          }
        })
      }).catch(_ => {
      });
    },
    handleUpdate(param) {
      this.dataTitle = '分类信息修改'
      this.dataFlag = true
      this.$nextTick(() => {
        this.$refs['dataDetails'].resetFields()
        this.dataDetails = JSON.parse(JSON.stringify(param))
        initCacheData()
        if (!isBlank(this.dataDetails.avatar)) {
          this.$store.state.avatarUrl = this.dataDetails.avatar
          this.$nextTick(() => {
            this.$refs['avatarUrl'].updateUrl()
          })
        }
      })
    },
    handleUpload() {
      this.dataTitle = '新增分类'
      this.dataFlag = true
      this.$nextTick(() => {
        this.$refs['dataDetails'].resetFields()
        initCacheData()
        let data = {}
        Object.assign(data, this.$options.data.call(this))
        this.dataDetails = data.dataDetails
      })
    },
    async initData() {
      this.seriesId = this.$route.query.seriesId
    },
    async initFunctions() {
      if (isFlag(this.$store.state.initDataFlag, true)) {
        await this.initData()
        await this.change(this.pageNo)
      }
    }
  },
  activated() {
    this.initFunctions()
    this.$store.state.initDataFlag = false
    setTimeout(() => {
      this.$store.state.initDataFlag = true
    }, 300);
  },
  beforeRouteLeave(to, from, next) {
    beforeRouteLeave(to, from, next, this.routerPage)
  },
  beforeRouteEnter(to, from, next) {
    //进入页面时会默认执行钩子函数，函数名为change，不可更改默认函数，否则会影响全局
    beforeRouteEnterCopy(to, from, next)
  },
}
</script>
<style scoped>
/deep/ .el-button + .el-button {
  margin-left: 0px;
}

/deep/ .el-table th.el-table__cell {
  user-select: initial;
}
</style>
